package com.imooc.spark.streaming.kafka;


import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

/**
 * kafka生产者
 *
 * @author yuyon26@126.com
 * @description
 * @date 2018/10/18 23:16
 */
public class MyKafkaProducer extends Thread {

    private String topic;

    private Producer<String, String> producer;

    public MyKafkaProducer(String topic) {
        this.topic = topic;

        Properties props = new Properties();
        props.put("bootstrap.servers", MyKafkaProperties.BROKER_LIST);
        props.put("acks", "all");
        props.put("retries", 0);
        props.put("batch.size", 16384);
        props.put("linger.ms", 1);
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        producer = new KafkaProducer<String, String>(props);
    }


    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            String message = "message_" + i;
            producer.send(new ProducerRecord<String, String>(topic, Integer.toString(i), message));
            System.out.println("Send:" +message);
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        producer.close();
    }
}
